import sqlite3
import rsa
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
import backend.DID.En_Decrypt_Management as En_Decrypt_Management



def create_user():
    try:
        db_path = 'user.db'
        conn = sqlite3.connect(db_path)


        cursor = conn.cursor()
        create_user_table = """
        create table if not exists user(
            hash1 text not null,
            id text null,
            hash2 text not null,
            username text not null,
            password text not null,
            private_key text not null
        );
        """
        cursor.execute(create_user_table)
        conn.commit()
        cursor.close()
        conn.close()
        return True
    except Exception as e:
        print(f"DID: user数据库创建失败，错误：{e}")
        return False

def create_temporary_key_to_other():
    try:
        db_path = 'temporary_key_to_other.db'
        conn = sqlite3.connect(db_path)

        cursor = conn.cursor()
        create_temporary_key_to_other_table = """
        create table if not exists temporary_key_to_other(
            other_id text not null,                                   
            temporary_PrivateKey text not null
        );
        """
        cursor.execute(create_temporary_key_to_other_table)
        conn.commit()
        cursor.close()
        conn.close()
        return True
    except Exception as e:
        print(f"DID: temporary_key_to_other数据库创建失败，错误：{e}")
        return False

def create_temporary_key_other_to_me():
    try:
        db_path = 'temporary_key_other_to_me.db'
        conn = sqlite3.connect(db_path)

        db_path = 'temporary_key_other_to_me.db'
        conn = sqlite3.connect(db_path)

        cursor = conn.cursor()
        create_temporary_key_other_to_me_table = """
        create table if not exists temporary_key_other_to_me(
            other_id text not null,                                   
            other_id text not null,                                   
            temporary_PrivateKey text not null
        );
        """
        cursor.execute(create_temporary_key_other_to_me_table)
        conn.commit()
        cursor.close()
        conn.close()
        return True
    except Exception as e:
        print(f"DID: temporary_key_other_to_me数据库创建失败，错误：{e}")
        return False





def insert_data(db_path, table_name, data):
    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()

        columns = ', '.join(data.keys())
        placeholders = ', '.join(['?'] * len(data))
        values = tuple(data.values())

        insert_query = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
        cursor.execute(insert_query, values)

        conn.commit()
        cursor.close()
        conn.close()
        return True
    except Exception as e:
        print(f"DID: {table_name}数据插入失败，错误：{e}")
        return False


def search_data(db_path, table, condition_column, condition_value,data):
    try:
        conn = sqlite3.connect(db_path)
        select_meg = f"SELECT {data} FROM {table} WHERE {condition_column} = ?"
        cursor = conn.cursor()
        cursor.execute(select_meg, (condition_value,))
        result = cursor.fetchall()
        conn. close()
        # print(result)
        s_data = result[0][0]
        return s_data
        # print(result)
        s_data = result[0][0]
        return s_data
    except Exception as e:
        print(f"DID:{table} 数据库查找失败，错误：{e}")
        return False

def search_hash1():
    try:
        the_path = 'user.db'
        conn = sqlite3.connect(the_path)
        table="user"
        select_hash1 = f"SELECT hash1 FROM {table} limit 1 "
        cursor = conn.cursor()
        cursor.execute(select_hash1)
        result = cursor.fetchall()
        conn.close()
        hash_value = result[0][0]
        return hash_value
    except Exception as e:
        print(f"DID:数据库查找hash1失败，错误：{e}")
        return False

def search_did():
    try:
        the_path = 'user.db'
        conn = sqlite3.connect(the_path)
        table="user"
        select_id = f"SELECT id FROM {table} limit 1 "
        cursor = conn.cursor()
        cursor.execute(select_id)
        result = cursor.fetchall()
        conn.close()
        s_data = result[0][0]
        return s_data
    except Exception as e:
        print(f"DID:数据库查找did失败，错误：{e}")
        return False

def private_key_changes(did):
    the_path = 'user.db'
    table = 'user'
    password = search_data(the_path, table, 'id', did, 'password')
    private_key = search_data(the_path, table, 'id', did, 'private_key')
    # print(f"[DID] private_key_changes  password: {password}, private_key: {private_key}")

    private_key_decrypt = En_Decrypt_Management.decrypt_privatekey(private_key, password).encode('utf-8')
    privatekey = rsa.PrivateKey.load_pkcs1(private_key_decrypt)
    return privatekey


def main():
    create_user()
    create_temporary_key_to_other()
    create_temporary_key_other_to_me()

if __name__ == "__main__":
    main()


